package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.GwAgent;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.vo.AgentVO;
import com.ruoyi.system.mapper.GwAgentMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.BaseService;
import com.ruoyi.system.service.IGwAgentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 代理商Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-07
 */
@Service
public class GwAgentServiceImpl extends BaseService implements IGwAgentService
{
    @Resource
    private GwAgentMapper gwAgentMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private SysUserRoleMapper userRoleMapper;

    private static final String AGENT_ROLE_KEY = "agent_role";

    private static final String AVATAR = "https://gowork365.com/prod-api/profile/mini/index/enterpriseLogo.png";

    /**
     * 查询代理商
     * 
     * @param id 代理商主键
     * @return 代理商
     */
    @Override
    public GwAgent selectGwAgentById(String id)
    {
        return gwAgentMapper.selectGwAgentById(id);
    }

    /**
     * 查询代理商列表
     * 
     * @param gwAgent 代理商
     * @return 代理商
     */
    @Override
    public List<GwAgent> selectGwAgentList(GwAgent gwAgent)
    {
        return gwAgentMapper.selectGwAgentList(gwAgent);
    }

    /**
     * 新增代理商
     * 
     * @param gwAgent 代理商
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertGwAgent(GwAgent gwAgent)
    {
        if(!checkPhone(gwAgent.getPhone())){
            return AjaxResult.error("该手机号已注册过，不可重复注册");
        }

        gwAgent.setId(IdUtils.fastSimpleUUID());
        gwAgent.setCreateBy(SecurityUtils.getUserId()+"");
        gwAgent.setCreateTime(DateUtils.getNowDate());
        int num = gwAgentMapper.insertGwAgent(gwAgent);
        //统一登录账号管理，将账号插入sys_user一份
        SysUser sysUser = new SysUser();
        sysUser.setUserType(UserType.AGENT_USER.getCode());
        sysUser.setPhonenumber(gwAgent.getPhone());
        sysUser.setNickName(gwAgent.getAgentName());
        sysUser.setPassword(SecurityUtils.encryptPassword(gwAgent.getPassword()));
        sysUser.setChannelId(gwAgent.getId());
        sysUser.setAvatar(AVATAR);
        sysUserMapper.insertUser(sysUser);

        //赋PC端角色
        saveSole(AGENT_ROLE_KEY,sysUser.getUserId());

        return AjaxResult.success();
    }

    /**
     * 修改代理商
     * 
     * @param gwAgent 代理商
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateGwAgent(GwAgent gwAgent)
    {
        gwAgent.setUpdateBy(SecurityUtils.getUserId()+"");
        gwAgent.setUpdateTime(DateUtils.getNowDate());
        int num = gwAgentMapper.updateGwAgent(gwAgent);
        //同步修改sys_user 账号信息
        SysUser sysUser = sysUserMapper.selectUserByChannelId(gwAgent.getId());
        if(sysUser!=null){
            sysUser.setPhonenumber(gwAgent.getPhone());
            sysUser.setNickName(gwAgent.getAgentName());
            sysUser.setPassword(SecurityUtils.encryptPassword(gwAgent.getPassword()));
            sysUserMapper.updateUser(sysUser);
        }
        return num;
    }

    /**
     * 批量删除代理商
     * 
     * @param ids 需要删除的代理商主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteGwAgentByIds(String[] ids)
    {
        int num = gwAgentMapper.deleteGwAgentByIds(ids);
        for(String id:ids){
            SysUser sysUser  = sysUserMapper.selectUserByChannelId(id);
            if(sysUser!=null){
                sysUserMapper.deleteUserById(sysUser.getUserId());
            }
        }
        return num;
    }

    /**
     * 删除代理商信息
     * 
     * @param id 代理商主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteGwAgentById(String id)
    {
        int num = gwAgentMapper.deleteGwAgentById(id);
        SysUser sysUser  = sysUserMapper.selectUserByChannelId(id);
        if(sysUser!=null){
            sysUserMapper.deleteUserById(sysUser.getUserId());
        }
        return num;
    }

    @Override
    public List<AgentVO> getList(GwAgent gwAgent) {
        return gwAgentMapper.getList(gwAgent);
    }

    private void saveSole(String roleKey,Long userId){
        //赋PC端角色
        SysRole sysRole = new SysRole();
        sysRole.setRoleKey(roleKey);
        List<SysRole> roleList = roleMapper.selectRoleList(sysRole);
        if(!CollectionUtils.isEmpty(roleList)){
            sysRole = roleList.get(0);
            List<SysUserRole> list = new ArrayList<SysUserRole>(1);
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(sysRole.getRoleId());
            userRole.setUserId(userId);
            list.add(userRole);
            userRoleMapper.batchUserRole(list);
        }
    }
}
